package leetcode.array;

import java.util.HashMap;

/**
 * @author Cheng Jun Description: https://leetcode.cn/problems/roman-to-integer/
 * @version 1.0
 * @date 2022/7/18 11:06
 * @see intToRoman
 */
public class romanToInt {
  private static HashMap<Character, Integer> romanNumMap = new HashMap<>(8);

  public static void main(String[] args) {
    // 创建一份字典，字符和数值的对应关系
    romanNumMap.put('I', 1);
    romanNumMap.put('V', 5);
    romanNumMap.put('X', 10);
    romanNumMap.put('L', 50);
    romanNumMap.put('C', 100);
    romanNumMap.put('D', 500);
    romanNumMap.put('M', 1000);
  }

  public static int romanToInt(String s) {
    // 六种特殊情况的判断
    int res = sixCase(s);
    if (res != 0) return res;
    // 正常逻辑的判断
    for (int i = 0; i < s.length() - 1; i++) {
      int special = sixCase(s.substring(i, i + 2));
      if (special == 0) {
        res += romanNumMap.get(s.charAt(i));
      } else {
        res += special;
        i++;
        if (i == s.length() - 1) return res;
      }
    }
    res += romanNumMap.get(s.charAt(s.length() - 1));
    return res;
  }

  private static int sixCase(String s) {
    // 六种特殊情况的判断
    switch (s) {
      case "IV":
        return 4;
      case "IX":
        return 9;
      case "XL":
        return 40;
      case "XC":
        return 90;
      case "CD":
        return 400;
      case "CM":
        return 900;
      default:
        return 0;
    }
  }

  // 推荐
  static int romanToInt1(String s) {
    int sum = 0;
    int preNum = romanNumMap.get(s.charAt(0));
    for (int i = 1; i < s.length(); i++) {
      int num = romanNumMap.get(s.charAt(i));
      if (preNum < num) {
        sum -= preNum;
      } else {
        sum += preNum;
      }
      preNum = num;
    }
    sum += preNum;
    return sum;
  }

  // 还有一种解法，利用 String的replace方法替换掉出现6种特殊情况，同时将字典扩充到13个特例。
}
